package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.common.CookieUtils;
import cn.wolfcode.shop.cloud.common.JSONUtil;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.redis.key.SeckillRedisKey;
import cn.wolfcode.shop.cloud.redis.key.UserRedisKey;
import cn.wolfcode.shop.cloud.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Created by wolfcode-lanxw
 */
@RestController
@RequestMapping("/api/verify/code")
public class VerifyCodeController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping
    public void generate(Long seckillId, @CookieValue(CookieUtils.USER_IN_TOKEN) String token, HttpServletResponse resp) throws IOException {
        // 1. 生成验证码表达式: 1+2
        String exp = VerifyCodeImgUtil.generateVerifyCode();
        // 2. 计算你验证码表达式的结果: 3
        Integer ret = VerifyCodeImgUtil.calc(exp);
        // 3. 将验证码结果存储到 redis, key 为 秒杀id+用户id
        User user = this.findUserByToken(token);
        redisTemplate.opsForValue().set(
                SeckillRedisKey.SECKILL_VERIFY_CODE.join(seckillId + "", user.getId() + ""),
                ret + "",
                SeckillRedisKey.SECKILL_VERIFY_CODE.getExpireTime(),
                SeckillRedisKey.SECKILL_VERIFY_CODE.getUnit());
        // 4. 基于验证码表达式生成验证码图片
        BufferedImage image = VerifyCodeImgUtil.createVerifyCodeImg(exp);
        // 5. 将图片通过响应流返回给前端
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(image, "JPEG", out);
    }

    private User findUserByToken(String token) {
        String json = redisTemplate.opsForValue().get(UserRedisKey.USER_TOKEN.join(token));
        return JSONUtil.parseObject(json, User.class);
    }
}
